var roleData = [], roleOpt = [];
// 配置
var id = {
    form: 'base_user_form',
    table: 'base_user_table',
};
var base_user = {
    query:[
        {code:1, type:'text', field:'key', title:'关键字', placeholder:'请输入关键字查询'}
    ],
    form: {
        id: id.form,
        form: [
            {code:1, type:'text', field:'loginName', title:'登录账号', placeholder:'请输入登录名'},
            {code:1, type:'password', field:'password', title:'登录密码', placeholder:'请输入登录密码'},
            {code:1, type:'text', field:'trueName', title:'姓名', placeholder:'请输入姓名'},
            {code:2, title:'性别',items:[
                    {field:'sex', value:'1', title:'男', type:'radio'},
                    {field:'sex', value:'0', title:'女', type:'radio'}
                ]},
            {code:1, type:'text', field:'nickName', title:'昵称', placeholder:'请输入昵称'},
            {code:1, type:'text', field:'phone', title:'手机', placeholder:'请输入手机'},
            {code:1, type:'text', field:'email', title:'电子邮箱', placeholder:'请输入电子邮箱'},
            {code: 8, field: 'avatar', title: '头像'},
        ]
    },
    update: {
        id: id.form,
        form: [
            {code:1, type:'text', field:'loginName', title:'登录账号', placeholder:'请输入登录名'},
            {code:1, type:'text', field:'trueName', title:'姓名', placeholder:'请输入姓名'},
            {code:2, title:'性别',items:[
                    {field:'sex', value:'1', title:'男', type:'radio'},
                    {field:'sex', value:'0', title:'女', type:'radio'}
                ]},
            {code:1, type:'text', field:'nickName', title:'昵称', placeholder:'请输入昵称'},
            {code:1, type:'text', field:'phone', title:'手机', placeholder:'请输入手机'},
            {code:1, type:'text', field:'email', title:'电子邮箱', placeholder:'请输入电子邮箱'},
            {code: 8, field: 'avatar', title: '头像'}
        ]
    },
    table: {
        id: id.table,
        url: api.base.user,
        cols:[
            {fixed: 'left',field: 'loginName', title: '登录名',minWidth: 120},
            {fixed: 'left',field: 'avatar', title: '头像', templet: function (obj) {
                    let avatar = obj.avatar;
                    if(avatar == ''){
                        if(obj.sex == 1){
                            avatar = '/assets/images/sex-1.png';
                        }else{
                            avatar = '/assets/images/sex-0.png';
                        }
                    }
                    return '<img src="' + avatar + '" width="32" height="32">'
                }},
            {fixed: 'left',field: 'trueName', title: '姓名',minWidth: 120},
            {fixed: 'left',field: 'id', title: '角色',minWidth: 120,templet: function (obj){
                    if(obj.role.length == 0){
                        return '<span data-id="' + obj.id + '" style="color:red;" onclick="base_user_view.role(this)"> 配置角色 </span>'
                    }else{
                        let role = [];
                        let ids = [];
                        for(var i=0;i<obj.role.length;i++){
                            role.push(obj.role[i].name);
                            ids.push(obj.role[i].id);
                        }
                        return '<span data-id="' + obj.id + '" data-val="'+ ids.join(',') +'" style="color:green;" onclick="base_user_view.role(this)"> ' + role.join(',') + ' </span>'
                    }
                }
            },
            {field: 'phone', title: '电话',minWidth: 120},
            {field: 'nickName', title: '昵称',minWidth: 120},
            {field: 'sex', title: '性别', templet: function (obj) {
                    return obj.sex == 1 ? '男' : '女';
                }},
            {field: 'email', title: '电子邮件',minWidth: 120},
            {field: 'state', title: '状态', templet: function (obj) {
                    return obj.state == 0 ? '<span style="color:green;" onclick="base_user_view.state(\''+obj.id+'\')">正常</span>' :
                        '<span style="color:red;" onclick="base_user_view.state(\''+obj.id+'\')">冻结</span>';
                }},
            {fixed: 'right', title: '操作', minWidth: 200, toolbar: page_auth.right()}
        ],
        toolbar: page_auth.top(),
        bar: function(bar){
            switch (bar.event) {
                case 'create':
                    base_user_view.form();
                    break;
                case 'search':
                    table.reload(id.table, {
                        page: {
                            curr: 1
                        },
                        where: soda.search.form()
                    });
                    break;
            }
        },
        tool: function (tool) {
            switch (tool.event) {
                case 'update':
                    base_user_view.form(tool.data)
                    break;
                case 'delete':
                    base_user_view.delete(tool.data.id)
                    break;
                case 'init':
                    base_user_view.init(tool.data.id);
                    break;
            }
        },
    }
}

// 初始化
initialize({
    module:['upload', 'common_upload', 'formSelects'],
    title: '用户管理',
    init: function () {
        soda.search.init(base_user.query);
        base_user_data.role.get();
        soda.table.render(base_user.table, true);
    }
})


// view
var base_user_view = {
    form: function (_data) {
        app.form({
            title:'数据管理',
            height: '80%',
            finish: function(){     // 点击确认后执行
                table.reload(id.table, {});
            },
            init: function () {
                if(_data){
                    soda.form.render(base_user.update);
                    soda.convert.formatFormData(0, base_user.update.form, _data ? _data : {});
                    soda.form.set(id.form, _data);
                    $('#loginName').attr('disabled', 'disabled')
                }else{
                    soda.form.render(base_user.form);
                    soda.convert.formatFormData(0, base_user.form.form, _data ? _data : {});
                }
                soda.form.set(id.form, {sex: 1});
            },
            opt: function () {
                let form = soda.form.get(id.form);  // 获取这个表单的数据
                let vfield = ['loginName', 'password'];
                if(_data){
                    vfield = [];
                }
                let v = soda.form.verify(form, id.form, vfield);  // 非空校验
                // form对象处理
                soda.convert.formatFormData(0, base_user.form.form, form, true)

                if(!v.check){
                    soda.tips.warning(v.message);
                    return false
                }
                if(vfield.length > 0){
                    if(form.password.length < 6 || form.password.length > 15){
                        soda.tips.warning('密码长度必须为6-15位之间');
                        return false
                    }
                }

                // 数据处理
                if(form.id){
                    base_user_data.update(form);
                }else{
                    base_user_data.create(form);
                }
            }
        })
    },
    delete: function (_id) {
        soda.tips.confirm({
            text: '确定要删除选中的数据吗?',
            confirm: function () {
                base_user_data.delete(_id);
            }
        });
    },
    role: function (_obj) {
        let userId = $(_obj).attr('data-id');
        let dataVal = $(_obj).attr("data-val");
        app.page({
            title: '角色分配',
            url: '/components/base/user_role.html',
            height: '420px',
            finish: function () {
                table.reload(id.table, {});
            },
            init: function () {
                var $arr = [];
                if(roleData.length > 0){
                    for(let i=0;i<roleData.length;i++){
                        let model = roleData[i];
                        let obj = {'name': model['name'], 'value': model['id']};
                        $arr.push(obj);
                    }
                }
                formSelects.data('user-select-role', 'local', {
                    arr: $arr
                });

                let roles = [];
                if((typeof dataVal) != "undefined"){
                    let item = dataVal.split(',');
                    for(let i=0;i<item.length;i++){
                        roles.push(item[i] + '');
                    }
                }

                formSelects.value('user-select-role', roles);
            },
            opt: function () {
                let vals = formSelects.value('user-select-role');
                base_user_data.role.set(vals, userId);
            }
        })
    },
    init: function(_id){
        soda.tips.confirm({
            text: '确定要重置当前用户密码吗?',
            confirm: function () {
                base_user_data.init(_id);
            }
        });
    },
    state: function(_id){
        soda.tips.confirm({
            text: '是否要调整当前用户状态?',
            confirm: function () {
                base_user_data.state(_id);
            }
        });
    }
}

// business
var base_user_data = {
    create: function (_form) {
        let param = {
            url: api.base.user,
            data: _form,
            callback: function () {
                app.finishForm();
            }
        }
        return soda.http.post(param);
    },
    update: function(_form){
        let param = {
            url: api.base.user + '/' + _form.id,
            data: _form,
            callback: function () {
                app.finishForm();
            }
        }
        return soda.http.put(param);
    },
    delete: function (_id) {
        let param = {
            url: api.base.user + '/' + _id,
            callback: function () {
                table.reload(id.table, {});
            }
        }
        return soda.http.delete(param);
    },
    role: {
        get: function () {
            let param = {
                url: api.system.role,
                tips: 0,
                isAll: true,
                callback: function (d) {
                    roleData = d.data;
                }
            }
            return soda.http.get(param);
        },
        set: function (_obj, _userId) {
            let param = {
                url: api.base.user + '/role/' + _userId,
                data: _obj,
                callback: function () {
                    app.finishForm();
                }
            }
            return soda.http.put(param);
        }
    },
    init: function(_id){
        let param = {
            url: api.base.user + '/pwd/' + _id + "/1",
            callback: function () {
                app.finishForm();
            }
        }
        return soda.http.put(param);
    },
    state: function(_id){
        let param = {
            url: api.base.user + '/state/' + _id,
            callback: function () {
                table.reload(id.table, {});
                app.finishForm();
            }
        }
        return soda.http.put(param);
    }
}

// controller
var base_user_opt = {
    update: function () {
        let selected = soda.table.check(id.table);
        if(selected.data.length != 1){
            soda.tips.warning('请选择一条数据进行编辑(仅能选择一条数据)');
            return false;
        }
        let row = selected.data[0];
        base_user_view.form(row);
    },
    delete: function () {
        let selected = soda.table.check(id.table);
        if(selected.data.length == 0){
            soda.tips.warning('至少要选择一条数据操作');
            return false;
        }
        let ids = soda.json.getVal(selected.data)
        base_user_view.delete(ids);
    }
}

